/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.bpmn.behavior;

import com.je.bpm.core.model.MessageEventDefinition;
import com.je.bpm.engine.delegate.DelegateExecution;
import com.je.bpm.engine.delegate.event.impl.ActivitiEventBuilder;
import com.je.bpm.engine.impl.bpmn.parser.factory.MessageExecutionContext;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.delegate.ThrowMessage;
import com.je.bpm.engine.impl.delegate.ThrowMessageDelegate;
import com.je.bpm.engine.impl.delegate.invocation.DelegateInvocation;
import com.je.bpm.engine.impl.delegate.invocation.ThrowMessageDelegateInvocation;

import java.util.Optional;

public abstract class AbstractThrowMessageEventActivityBehavior extends FlowNodeActivityBehavior {

    private static final long serialVersionUID = 1L;

    private final MessageEventDefinition messageEventDefinition;
    private final ThrowMessageDelegate delegate;
    private final MessageExecutionContext messageExecutionContext;

    public AbstractThrowMessageEventActivityBehavior(MessageEventDefinition messageEventDefinition,
                                                     ThrowMessageDelegate delegate,
                                                     MessageExecutionContext messageExecutionContext) {
        this.messageEventDefinition = messageEventDefinition;
        this.delegate = delegate;
        this.messageExecutionContext = messageExecutionContext;
    }

    protected boolean send(DelegateExecution execution, ThrowMessage message) {
        DelegateInvocation invocation = new ThrowMessageDelegateInvocation(delegate, execution, message);
        Context.getProcessEngineConfiguration()
                .getDelegateInterceptor()
                .handleInvocation(invocation);

        return (boolean) invocation.getInvocationResult();
    }

    ;

    @Override
    public void execute(DelegateExecution execution) {
        ThrowMessage throwMessage = getThrowMessage(execution);

        boolean isSent = send(execution, throwMessage);

        if (isSent) {
            dispatchEvent(execution, throwMessage);
        }

        super.execute(execution);
    }

    public MessageEventDefinition getMessageEventDefinition() {
        return messageEventDefinition;
    }

    protected ThrowMessage getThrowMessage(DelegateExecution execution) {
        return messageExecutionContext.createThrowMessage(execution);
    }

    protected void dispatchEvent(DelegateExecution execution, ThrowMessage throwMessage) {
        Optional.ofNullable(Context.getCommandContext())
                .filter(commandContext -> commandContext.getProcessEngineConfiguration()
                        .getEventDispatcher()
                        .isEnabled())
                .ifPresent(commandContext -> {
                    String messageName = throwMessage.getName();
                    String correlationKey = throwMessage.getCorrelationKey()
                            .orElse(null);
                    Object payload = throwMessage.getPayload()
                            .orElse(null);

                    commandContext.getProcessEngineConfiguration()
                            .getEventDispatcher()
                            .dispatchEvent(ActivitiEventBuilder.createMessageSentEvent(execution,
                                    messageName,
                                    correlationKey,
                                    payload));
                });
    }

    public ThrowMessageDelegate getDelegate() {
        return delegate;
    }

    public MessageExecutionContext getMessageExecutionContext() {
        return messageExecutionContext;
    }
}
